import { ref } from 'vue';
import { fetchViewportList } from '@src/api/Viewport';
import i18n from '@src/locales';

export type ViewportSearchModelItemType = {
  fieldName: string,
  operator: string,
  value: any,
}

export type ViewportType = {
  viewId?: string;
  module?: string; // 模块
  viewName: string; // 视图名称
  searchModel: ViewportSearchModelItemType[]; // 视图查询条件
  authEdit?: boolean; // 是否可编辑 视图列表才有目前用来区分是否个人（只有自己的视图才能编辑）
  visibleType: 0 | 1; // 是否全员可见
  viewNo?: string;
  url?: string;
};

const defaultView: ViewportType = {
  viewId: '',
  viewName: i18n.t('component.viewportDropdown.defaultName') as string,
  searchModel: [],
  authEdit: false,
  visibleType: 1,
  viewNo: '',
  url: '',
};

export function useViewport(module: string, preViews = []) {
  const activeViewport = ref<ViewportType>(defaultView);
  const list = ref<ViewportType[]>([defaultView]);

  /**
   * 查询视图列表
   * @param {String} module 模块
   */
  const getList = async () => {
    try {
      const _list = await fetchViewportList(module);
      return (list.value = [defaultView, ...preViews, ..._list]);
    } catch (error) {
      console.log(error);
      return Promise.reject(error);
    }
  };

  /**
   * 选中视图
   * @param {ViewportType} _v
   */
  const chooseViewport = (_v: ViewportType = defaultView) => {
    activeViewport.value = _v;
  };

  const removeViewport = (index: number) => {
    if (index === 0 || !list.value[index]) return;
    if (list.value[index].viewId === activeViewport.value.viewId) {
      // 删除当前选中视图，切换到默认视图
      chooseViewport();
      return true;
    }
    list.value.splice(index, 1);
  };

  return {
    activeViewport,
    list,
    getList,
    chooseViewport,
    removeViewport,
  };
}
